/* ************************************************************************ */
/*                                                                          */
/*  Copyright (c)2005 Russell Weir | damonsbane _at_ gmail                  */
/*                                                                          */
/* This library is free software; you can redistribute it and/or            */
/* modify it under the terms of the GNU Lesser General Public               */
/* License as published by the Free Software Foundation; either             */
/* version 3.0 of the License, or (at your option) any later version.       */
/*                                                                          */
/* This library is distributed in the hope that it will be useful,          */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of           */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        */
/* Lesser General Public License or the LICENSE file for more details.      */
/*                                                                          */
/* ************************************************************************ */

package tzparser;
import altdate.TimeSpecification;

enum ZoneRuleType {
	EMPTY;
 	TIME;
 	CHAIN;
}

class ZoneRule {
	public var utcOffset(default,null)	: TimeSpecification;
	public var rulefield(default,null)		: Dynamic;
	public var format(default,null)		: ZoneFormat;
	public var until(default,null)		: Until;
	public var type(default,null)		: ZoneRuleType;
	public var chain(default,null)	: RuleSet;

	public function new(
		utcOffset:TimeSpecification,
		rulefield : String,
		format : ZoneFormat,
		until : Until)
	{
		this.type = EMPTY;
		this.utcOffset = utcOffset;
		checkRule(rulefield);
		this.format = format;
		this.until = until;
	}

	// TODO: the chained rules should be loaded in.
	// this will require either 1) Parsing rules first == or ==
	// 2) Finalizing all ZoneRules after parsing file.
	function checkRule(atom:String) {
		if(atom == "-") {
			type = EMPTY;
			rulefield = null;
			return;
		}
		var ereg = ~/[A-Za-z]+/;
		if(ereg.match(atom)) {
			type = CHAIN;
			rulefield = atom;
			return;
		}
		type = TIME;
		rulefield = TimeSpecification.parse(atom);
	}

	public function isChained() : Bool {
		return if(type == CHAIN) true else false;
	}

	public function getStdOffset() : TimeSpecification {
		if(type != TIME)
			return new TimeSpecification();
		return rulefield;
	}

	public function finalize() : Void {
		if(type != CHAIN)
			return;
		var tmp = rulefield;
		this.chain = Parser.getInstance().rules.get(this.rulefield);
		if(this.chain == null) {
			throw "Rule Set "+ Std.string(tmp) + " not found";
		}
	}
}